package com.nulldev.util.uri.yt.extraction.related;

import java.net.Proxy;
import java.nio.charset.Charset;
import java.util.ArrayList;

import com.nulldev.util.other.CharsetUtil;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.URIUtil2;
import com.nulldev.util.uri.Soup_imported.Jsoup;
import com.nulldev.util.uri.Soup_imported.nodes.Document;
import com.nulldev.util.uri.Soup_imported.nodes.Element;
import com.nulldev.util.uri.Soup_imported.select.Elements;
import com.nulldev.util.uri.yt.MetadataExtractor;

public class Parser {
	//Tags and attributs for serching video's info
    static String VIDEO_TAG = "video-list-item";
    static String VIDEO_ID = "data-video-ids";
    static String TAG_A = "a";
    static String ATTR_HREF = "href";
    static String ATTR_CLASS = "class";
    static String CLASS_TITLE = "title";
    static String CLASS_USER = "yt-user-name";
    static String CLASS_USER_2 = "stat attribution";
    static String CLASS_TIME = "video-time";
    static String CLASS_VIEWS = "stat view-count";

    /**
     * Get Document from url from some Connector and parse it.
     *
     * @param url the URL of YouTube page
     * @return the arrayList of videoInfos
     * @throws IOException If an input or output exception occurred
     * @see VideoInfo
     */
    public static ArrayList<VideoInfo> parse(final String data) throws Exception{
        final ArrayList<VideoInfo> videoInfos = new ArrayList<VideoInfo>();
        String pageData = data; //URIUtil.downloadPageNEncoding(
        		//URIUtil.safeCreate(url), true, Proxy.NO_PROXY, URIUtil2.URI_UTIL2_USER_AGENT);
        /* if (pageData.contains("og:restrictions:age")) {
        	pageData = URIUtil.downloadPageNEncoding(
        			URIUtil.safeCreate(url + "&has_verified=1"), true, Proxy.NO_PROXY, URIUtil2.URI_UTIL2_USER_AGENT);
        }else if (pageData.contains("verify_controversy")) {
        	pageData = URIUtil.downloadPageNEncoding(
        			URIUtil.safeCreate(url + "&bpctr=" + System.currentTimeMillis()), true, Proxy.NO_PROXY, URIUtil2.URI_UTIL2_USER_AGENT);
        }*/
        Document document = Jsoup.parse(pageData);
        Elements elements = document.getElementsByClass(VIDEO_TAG);
        //Getting video's info
        for (Element element : elements) {
            String link = getLink(element);
            String name = element.getElementsByAttributeValue(ATTR_CLASS, CLASS_TITLE).text();
            String user = element.getElementsByAttributeValueMatching(ATTR_CLASS, CLASS_USER).text();
            if (user == null || user.equals("")) {
            	user = element.getElementsByAttributeValueMatching(ATTR_CLASS, CLASS_USER_2).text();
            }
            String time = element.getElementsByAttributeValue(ATTR_CLASS, CLASS_TIME).text();
            String views = element.getElementsByAttributeValue(ATTR_CLASS, CLASS_VIEWS).text();
            final VideoInfo vi = new VideoInfo(name, link, user, time, views);
            if (name.startsWith("Mix - ") && (user.equals("") || user.equals("YouTube") ||
            		user.equals("YouTube Movies")) && time.equals("") && views.equals("")) {
            }else {
//            	try {
//            		if (vi.getUser() == null || vi.getUser().equals("")) {
//                		vi.___setUser(MetadataExtractor.getMeta(URIUtil.safeCreate("https://www.youtube.com/watch?v=" + link)).getAuthor());
//                	}
//            	}catch (Exception e) {}
            	videoInfos.add(vi);
            }
        }
        return videoInfos;
    }

    /**
     * Getting link of video
     *
     * @param element the html tags which contain video's info
     * @return the ID of video
     */
    private static String getLink(Element element) {
        String result = element.getElementsByAttribute(VIDEO_ID).attr(VIDEO_ID);
        //Another link search for special case
        if (result.equals("")) {
            String[] strings = element.getElementsByTag(TAG_A).attr(ATTR_HREF).split("=");
            String prev = "";
            for (String str : strings) {
                if (str.endsWith("&list")) {
                    result = str.split("&")[0];
                    break;
                }else if (prev.equals("/watch?v")) {
                	return str;
                }else {
                	prev = str;
                }
            }
        }
        return result;
    }
}
